<?php
// +----------------------------------------------------------------------
// | Author: yaoyihong <510974211@qq.com>
// +----------------------------------------------------------------------
namespace app\tcms\logic;
use \tpfcore\Core;
use tpfcore\util\Data;
use think\Session;

class User extends FrontendBase
{
	public function login($data=[]){
		$validate=\think\Loader::validate($this->name);
		$validate_result = $validate->scene('login')->check($data);
        if (!$validate_result) {    
            return [40044, $validate->getError(), null];
        }
        $list = self::getOneObject(["username"=>$data['username'],"password"=>"###".md5($data['password'].DATA_ENCRYPT_KEY),"grade"=>0],"id,username,headimg,nickname,signature");

        if(empty($list)){
        	return [40045,"用户名或密码错误"];
        }

        session("tpf_login_sign",$list->toArray());

        $return_url=isset($data['return_url'])?$data['return_url']:url("h5shop/Index/index");

        return [0,"登录成功",$return_url];
	}
	public function reg($data=[]){
		$validate=\think\Loader::validate($this->name);
		$validate_result = $validate->scene('register')->check($data);
        if (!$validate_result) {    
            return [40044, $validate->getError(), null];
        }

        $result = Core::loadModel($this->name)->saveObject($data);

        if($result){

        	$user=["id"=>$result,"username"=>$data['username'],"password"=>"###".md5($data['password'].DATA_ENCRYPT_KEY)];

        	session("tpf_login_sign",$user);

        	return [0,"注册成功",url("h5shop/Index/index")];
        }else{

        	return [40045,"注册失败"];

        }
        
	}
	public function logout(){
		Session::delete("tpf_login_sign");
		return [RESULT_SUCCESS,"安全退出",url("h5shop/index/index")];
	}

	public function getUser($data=[]){
		return self::getList($data);
	}

	//更新用户信息
	public function updateUserInfo($data,$limit_field,$redirect_url="Member/index"){
		foreach ($data as $key => $value) {
			if(empty($value) && !is_numeric($value)){
				unset($data[$key]);
			}
		}
		$data['id']=session("tpf_login_sign")['id'];
		$result = self::saveObject($data,$limit_field);
		if($result){
			isset($data['nickname']) && session("tpf_login_sign.nickname",$data['nickname']);
			isset($data['headimg']) && session("tpf_login_sign.headimg",$data['headimg']);
			isset($data['signature']) && session("tpf_login_sign.headimg",$data['signature']);
			return [0,"操作成功",$redirect_url];
		}
		return [40040,"操作失败"];
	}
}